package tenant

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/common/utils"
	"git.mycaigou.com/gfyx/micro-gfyx-user-service/infrastructure/repository/tenant/tenant"
	pb "git.mycaigou.com/gfyx/micro-gfyx-user-service/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service/tenant"
	"git.myscrm.cn/golang/stark/v4"
)

type TenantService struct {
	tenantsRepository tenant.TenantsRepositoryIface
}

func NewTenantService(tenantsRepository tenant.TenantsRepositoryIface) TenantServiceIface {
	return &TenantService{tenantsRepository: tenantsRepository}
}

func (s *TenantService) GetTenantList(ctx context.Context, request *pb.GetTenantListRequest) (*pb.GetTenantListResponse, error) {
	condition := make(map[string]interface{})
	pageInfo := utils.PageInfo{
		PageSize: int(request.PageSize),
		Page:     int(request.Page),
	}
	total, list, err := s.tenantsRepository.QueryTenantList(ctx, condition, &pageInfo, "created_on desc")
	if err != nil {
		stark.Logger.Errorf(ctx, "GetTenantList error, err:%v", err)
		return nil, err
	}
	var data []*pb.Tenant
	for _, item := range list {
		data = append(data, &pb.Tenant{
			TenantCode: item.Code,
			TenantName: item.Name,
		})
	}
	return &pb.GetTenantListResponse{
		Total: total,
		List:  data,
	}, nil
}

func (s *TenantService) GetTenantByName(ctx context.Context, request *pb.GetTenantByNameRequest) (*pb.GetTenantByNameResponse, error) {
	data, err := s.tenantsRepository.GetTenantByName(ctx, request.Name)
	res := &pb.GetTenantByNameResponse{}
	if err != nil {
		stark.Logger.Errorf(ctx, "GetTenantByName error, err:%v", err)
		return res, err
	}
	res.Code = data.Code
	res.Name = data.Name
	res.MasterName = data.MasterName
	res.MasterEmail = data.MasterEmail
	res.MasterPhone = data.MasterPhone
	res.Enabled = data.Enabled
	res.Remark = data.Remark
	return res, nil
}

func (s *TenantService) GetTenantByCode(ctx context.Context, request *pb.GetTenantByCodeRequest) (*pb.GetTenantByCodeResponse, error) {
	data, err := s.tenantsRepository.GetTenantByCode(ctx, request.Code)
	res := &pb.GetTenantByCodeResponse{}
	if err != nil {
		stark.Logger.Errorf(ctx, "GetTenantByCode error, err:%v", err)
		return res, err
	}
	res.Code = data.Code
	res.Name = data.Name
	res.MasterName = data.MasterName
	res.MasterEmail = data.MasterEmail
	res.MasterPhone = data.MasterPhone
	res.Enabled = data.Enabled
	res.Remark = data.Remark
	return res, nil
}

func (s *TenantService) GetAllEfficientTenant(ctx context.Context, request *pb.GetAllEfficientTenantRequest) (*pb.GetAllEfficientTenantResponse, error) {
	total, data, err := s.tenantsRepository.GetAllEfficientTenant(ctx)
	res := &pb.GetAllEfficientTenantResponse{
		List:  make([]*pb.EfficientTenant, 0),
		Total: total,
	}
	if err != nil {
		stark.Logger.Errorf(ctx, "GetAllEfficientTenant error, err:%v", err)
		return res, err
	}
	for _, v := range data {
		res.List = append(res.List, &pb.EfficientTenant{Code: v.Code})
	}
	return res, nil
}
